package com.dhcc.core.framework.result.page;

import javax.servlet.http.HttpServletRequest;

import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.core.framework.constant.state.Order;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.framework.util.HttpContextUtil;

/**
 * BootStrap Table默认的分页参数创建
 * 
 * @ClassName: PageFactory
 * @Description: TODO
 * @author: cyf
 * @date: 2018年1月2日 上午9:30:25
 * @param <T>
 */
public class PageFactory<T> {
    /**
     * 从request里获取page查询信息，生成page
     * @Title: defaultPage 
     * @Description: TODO
     * @return
     * @return: Page<T>
     */
    public Page<T> defaultPage() {
        HttpServletRequest request = HttpContextUtil.getRequest();
        int limit = Integer.valueOf(request.getParameter("limit"));
        int offset = Integer.valueOf(request.getParameter("offset"));
        String sort = request.getParameter("sort");
        String order = request.getParameter("order");
        int pageNo = (offset / limit + 1);
        return defaultPage(pageNo, limit, sort, order);
    }
    /**
     * 
     * @Title: dataGridPage 
     * @Description: TODO
     * @return
     * @return: Page<T>
     */
    public Page<T> dataGridPage() {
        HttpServletRequest request = HttpContextUtil.getRequest();
        int limit = Integer.valueOf(request.getParameter("rows"));
        int offset = Integer.valueOf(request.getParameter("page"));
        String sort = request.getParameter("sort");
        String order = request.getParameter("order");
        int pageNo = (offset / limit + 1);
        return defaultPage(pageNo, limit, sort, order);
    }
    /**
     * 生成page
     * @Title: defaultPage 
     * @Description: TODO
     * @param pageNo 当前页
     * @param limit  记录数据
     * @param sort   排序字段
     * @param order  排序方式
     * @return
     * @return: Page<T>
     */
    public Page<T> defaultPage(int pageNo, int limit, String sort, String order) {
        if (CommonUtil.isEmpty(sort)) {
            Page<T> page = new Page<>(pageNo, limit);
            page.setOpenSort(false);
            return page;
        } else {
            // 驼峰转下划线
            sort = CommonUtil.camelToUnderline(sort);
            Page<T> page = new Page<>(pageNo, limit, sort);
            if (Order.ASC.getDes().equals(order)) {
                page.setAsc(true);
            } else {
                page.setAsc(false);
            }
            return page;
        }
    }
}
